package org.mspring.platform.counter;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.mspring.platform.counter.dao.CountDao;
import org.mspring.platform.counter.entity.Count;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @since 2014年4月25日
 * @author Gao Youbo
 */
@Service
@Transactional
public class CountService {
    @Autowired
    private CountDao countDao;

    @PostConstruct
    public void initTable() throws IOException {
        countDao.initTable();
    }

    public void insertOrUpdate(Count count) {
        if (count == null) {
            return;
        }
        if (StringUtils.isBlank(count.getCountKey()) || String.valueOf(count.getDay()).length() != 8) {
            return;
        }
        Count temp = countDao.findByDayAndCountKey(count.getDay(), count.getCountKey());
        if (temp != null) {
            temp.setCount(count.getCount());
            temp.setUpdateTime(new Date());
            countDao.update(temp);
        } else {
            count.setCreateTime(new Date());
            count.setUpdateTime(new Date());
            countDao.insert(count);
        }
    }

    public List<Count> listByDay(int day) {
        return countDao.listByDay(day);
    }

    public Count findByCountKey(String countKey) {
        return countDao.findByCountKey(countKey);
    }

    public long sumByCountKey(String countKey) {
        return countDao.sumByCountKey(countKey);
    }

}
